<template>
	<view class="container">
		<!-- 必须用button按钮，因为需要打开微信开放能力 -->
		<button type="success" open-type="getUserInfo" @getuserinfo="userInfoCallBack">授权微信登录</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			};
		},
		methods: {
			async userInfoCallBack(e){
				console.log(e)
				// 记录用户信息到本地缓存
				uni.setStorage({
					key: 'userInfo',
					data: e.detail.userInfo
				})
				// 获取加密数据
				const { encryptedData, iv, rawData, signature } = e.detail;
				// 获取code属性，通过登录接口获取
				const [error, res] = await uni.login()
				const { code } = res;
				// 发送网络请求登录
				const [LoginError, loginRes] = await uni.request({
					url: 'https://api-hmugo-web.itheima.net/api/public/v1/users/wxlogin',
					method: 'POST',
					data: {
						encryptedData, iv, rawData, signature, code
					}
				})
				if (loginRes.data.meta.status === 200) {
					// 登录成功，把token存储到本地
					uni.setStorageSync('token', loginRes.data.message.token)
					// 提示用户登录成功，并且返回上一页
					uni.showToast({
						icon: 'none',
						title: '登录成功'
					})
					uni.navigateBack()
				} else {
					uni.showToast({
						icon: 'none',
						title: '服务器异常，请重新点击登录'
					})
				}

			}
		}
	}
</script>

<style lang="less">
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		button {
			background: #07C160;
			border-radius: 8rpx;
			border-radius: 8rpx;
			font-size: 36rpx;
			width: 461rpx;
			height: 88rpx;
			color: #fff;
		}
	}
</style>